import { cloudDBZone, initCloudDB } from '@/AGC/manager'
import { CloudDBZoneQuery } from '@hw-agconnect/database'
import { ExercisePlan } from '@/AGC/model/ExercisePlan'
import { useUserStore } from '@/stores/user'

/**
 * 查询用户某一天的运动计划
 * @param user_id 用户id
 * @param date 日期
 * @returns 运动计划
 */
export const queryExercisePlan = async (date: string) => {
  if (!cloudDBZone) await initCloudDB()

  const query = await CloudDBZoneQuery.where(ExercisePlan)
  const user_id = useUserStore().userInfo.id
  query.equalTo('user_id', user_id).equalTo('date', date).orderByAsc('id')
  const snapshot = await cloudDBZone.executeQuery(query)
  return snapshot.getSnapshotObjects()
}

/**
 * 执行运动计划插入
 * @param list 运动计划列表
 */
export const executeUpsertExercisePlan = async (list: ExercisePlan | ExercisePlan[]) => {
  if (!cloudDBZone) await initCloudDB()

  const cloudDBResult = await cloudDBZone.executeUpsert(list)
  console.log('executeUpsertExercisePlan: ' + cloudDBResult)
}

/**
 * 清除用户的运动计划
 */
export const executeDeleteExercisePlan = async () => {
  if (!cloudDBZone) await initCloudDB()

  const query = await CloudDBZoneQuery.where(ExercisePlan)
  const user_id = useUserStore().userInfo.id
  query.equalTo('user_id', user_id)
  const snapshot = await cloudDBZone.executeQuery(query)
  const list = snapshot.getSnapshotObjects()
  await cloudDBZone.executeDelete(list)
}

/** 清除用户当天之后的运动计划 */
export const executeDeleteExercisePlanByDate = async (dateString: string) => {
  if (!cloudDBZone) await initCloudDB()

  const query = await CloudDBZoneQuery.where(ExercisePlan)
  const user_id = useUserStore().userInfo.id
  query.equalTo('user_id', user_id).greaterThan('date', dateString)
  const snapshot = await cloudDBZone.executeQuery(query)
  const list = snapshot.getSnapshotObjects()
  await cloudDBZone.executeDelete(list)
}
